<?php

namespace app\system\controller\customer;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use hehe\Numeral;
use hehe\Str;
use hehe\Trade;
use think\facade\Db;


class OrderList extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['corp_name_cn', 'corp_name_ko', 'manager'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\customer\OrderList;
    }

    /**
     * 删除代理商
     */
    public function delAgent() {
        $param = $this->request->param();
        $result = db::name('customer_order_agent')->where(['id' => $param['id']])->delete();
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }



    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $this->withJoinTable = ['product' => function($query){
            $query->leftJoin(['category']);
        }];
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->with(['product' => function($query){
                $query->with(['category']);
            }])
            ->alias($alias)
            ->where($where);
        $param = $this->request->param();
//        echo 1 ;die;

        if(!empty($param['order_id'])){
            $res = $res->where(['order_id' => $param['order_id']]);
        }


        $res = $res->order('id asc')->paginate($limit);
//        echo 1;die;

        $list = $res->items();

//        print_r($list);die;

        foreach($list as $key => $val){
            $list[$key]['sale_price'] = $val['sale_currency'] . ' ' . ($val['sale_price'] / $this->multiply);
            $list[$key]['cost_price'] = $val['cost_currency'] . ' ' . $val['cost_price'] / $this->multiply;
            $list[$key]['quantity'] = number_format($val['quantity'] / $this->multiply);
        }


        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

//            print_r($data);die;



            if(empty($data['product_id'])) $this->error(__('请选择产品'));

            $where = [
                'order_id' => $data['order_id'],
                'product_id' => $data['product_id']
            ];
            $detail = db::name('customer_order_detail')->where($where)->find();
            if($detail) $this->error(__('请勿重复下单'));


            $data['sale_price'] = empty($data['sale_price']) ? 0 : $data['sale_price'] * $this->multiply;
            $data['cost_price'] = empty($data['cost_price']) ? 0 : $data['cost_price'] * $this->multiply;
            $data['quantity'] = empty($data['quantity']) ? 0 : $data['quantity'] * $this->multiply;

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);

            if(empty($data['product_id'])) $this->error(__('请选择产品'));
            $data['sale_price'] = empty($data['sale_price']) ? 0 : $data['sale_price'] * $this->multiply;
            $data['cost_price'] = empty($data['cost_price']) ? 0 : $data['cost_price'] * $this->multiply;
            $data['quantity'] = empty($data['quantity']) ? 0 : $data['quantity'] * $this->multiply;

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $row['cost_price'] /= $this->multiply;
        $row['sale_price'] /= $this->multiply;
        $row['quantity'] /= $this->multiply;

        $this->success('', [
            'row' => $row
        ]);
    }



























}